import fetch from "../../utils/fetch";
const globalData = getApp().globalData;
const {
  gotoLogin
} = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    score:10,
    heatGoods: [],
    goods: []
  },

  size:10, //每次获取十个商品
  page:1, //第几次获取
  count:0,  //商品总数
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.page = 1;
    this.count = 0;
    this.size = 3;

    //获取商品列表
    this.getGoodsList(1,this.page,this.size).then(res=>{
      console.log(res);
      this.count = res.data.count;
      this.setData({
        heatGoods:res.data.heatGoods,
        goods:res.data.goodsArr,
        score:globalData.userInfo.score?globalData.userInfo.score:0
      })
    }).catch(err=>{
      console.log(err);
      this.onLoad();
    });
  },
    //获取商品列表
    getGoodsList:function(type,page,size){
      return fetch('/goods/list',{
        type,page,size
      });
    },
    getMoreGoods(){
      //获取更多商品
    if( this.page*this.size > this.count){
      return;
    } 
    this.page++;
    this.getGoodsList(2,this.page,this.size).then(res=>{
      let goods = this.data.goods;
      res.data.goodsArr.forEach(item=>{
        goods.push(item);
      });
      this.setData({
        goods,
      })
    })
    },

    gotoGoodsDetail(e){
      const goodsId = e.currentTarget.dataset.goodsId;
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?goodsId=' + goodsId,
    })
    },
    /**
   * 生命周期函数--监听页面显示
   */
  enableRefresh: false,  //该变量用于页面onshow重新获取文章数据，并且onload如果执行则不重复执行onshow
  onShow() {
    if(this.enableRefresh){
      this.page = 1;
      this.size = 10;
      this.getGoodsList(1,this.page,this.size).then(res=>{
        this.count = res.data.count;
        this.setData({
          heatGoods:res.data.heatGoods,
          goods:res.data.goodsArr,
          score:globalData.userInfo.score?globalData.userInfo.score:0
        })
      }).catch(err=>{
        this.onShow();
      });
    }else{
      this.enableRefresh = true;
    }
  },
  gotoMyGift(){
    if(!globalData.isLogin){
      gotoLogin();
      return;
    }
    wx.navigateTo({
      url: '../myGift/myGift',
    })
  },
  gotoScoreRule(){
    wx.navigateTo({
      url: '../scoreRule/scoreRule',
    })
  }
})